package main.二叉树;

import common.TreeNode;

/**
 * @author tmh
 * @date 2024/7/23 17:14
 * @description
 */
public class T236二叉树的最近公共祖先 {

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        //条件判断，如果root为null，或者root=p，或者root=q，返回root
        if (root == null || root == p || root == q) {
            return root;
        }
        //往左遍历
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        //往右遍历
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        //判断 //如果左为空，那么就返回右子树的结果right
        if (left == null) {
            return right;
        }
        //如果右为空，那么就返回左子树的结果
        if (right == null) {
            return left;
        }
        //如果左右子树都为空的话，那么就直接返回当前节点root
        return root;
    }
}
